package com.zjy.pet.service.impl;

import com.zjy.basic.exception.BusinessException;
import com.zjy.basic.service.BaiduAiAuditService;
import com.zjy.basic.util.*;
import com.zjy.order.domain.OrderPetAcquisition;
import com.zjy.pet.dto.OrderDto;
import com.zjy.order.mapper.OrderPetAcquisitionMapper;
import com.zjy.org.domain.Employee;
import com.zjy.org.domain.Shop;
import com.zjy.org.mapper.EmployeeMapper;
import com.zjy.org.mapper.ShopMapper;
import com.zjy.pet.domain.SearchMasterMsg;
import com.zjy.pet.domain.SearchMasterMsgAuditLog;
import com.zjy.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.zjy.pet.mapper.SearchMasterMsgMapper;
import com.zjy.pet.query.SearchMasterMsgQuery;
import com.zjy.pet.service.SearchMasterMsgService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import com.zjy.user.domain.Logininfo;
import com.zjy.user.domain.User;
import com.zjy.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {

    @Autowired
    private BaiduAiAuditService baiduAiAuditService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // name: '小七',
        // price: 10,
        // age: 3,
        // gender: 1,
        // coatColor: '黑色',
        // resources: null,
        // petType: 1,
        // address: null,
        // title: '小七寻主'
        // UserId -发布人 - request获取
        // shopId - 分配给哪一个店铺，审核通过之后再分配 - 现在不用管
        // note - 发布寻主消息的说明 - 不用管

        //一：空值校验忽略
        //二：先保存寻主消息 - 获取到了自增长id
        Logininfo logininfo = LoginContext.getLogininfo(request);//获取登录人信息
        User user = userMapper.findByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());//哪一个用户发布的寻主消息 - 登录这个用户
        searchMasterMsgMapper.add(searchMasterMsg);//自增id

        //三：智能审核
        //审核标题和宠物名
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        //审核上传的宠物图片
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        //提前生成审核日志对象(因为不论是否通过都要有审核的记录)
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();

        //判断审核是否通过
        if (boo1 && boo2){//通过
            //四：审核通过：1.改state=1 2.分配最近50公里以内的店铺 3.发短信或邮箱告诉店铺管理员去接回宠物 4.记录审核日志
            //1.改state=1
            searchMasterMsg.setState(1);

            //2.分配最近50公里以内的店铺(思路：先获取所有的店铺->调用工具类获取用户当前的位置->调用工具类获取离用户最近的店铺)
            //还要考虑店铺的状态 - 这里忽略了
            List<Shop> shops = shopMapper.findAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);

            if(nearestShop==null){//如果50公里以内没有店铺 => 到寻主池(寻主状态设置为3)
                searchMasterMsg.setState(3);
            }else {
                searchMasterMsg.setShopId(nearestShop.getId());
                //3.发短信或邮箱告诉店铺管理员去接回宠物
                Employee employee = employeeMapper.findById(nearestShop.getAdminId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
                System.out.println("你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
            }
            searchMasterMsg.setNote("审核通过");
            searchMasterMsgMapper.update(searchMasterMsg);

            //4.记录审核日志
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            //智能审核，没有审核人
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.add(log);

            return new AjaxResult();
        }else {
            //五：审核失败: 1.改状态state=-1 2.发短信或邮箱告诉用户重新修改资料再发布 3.记录审核日志
            //1.改state=-1
            searchMasterMsg.setState(-1);

            //2.发短信或邮箱告诉用户重新修改资料再发布
            //SmsUtils.sendSms(user.getPhone(),"你的消息审核失败，请重新修改之后再发布");
            System.out.println("你的消息审核失败，请重新修改之后再发布");

            //3.记录审核日志
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            //智能审核，没有审核人
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.add(log);

            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户不需要设置state，用户是查询自己的所有状态的寻主消息
        //想办法获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        System.out.println("logininfo:"+logininfo);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        System.out.println("query:"+query);
        System.out.println("user:"+user);
        query.setUserId(user.getId());
        //分页查询
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理的寻主消息
        query.setState(1);
        //用于区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //如果shopId is null = 平台管理员
        if (employee.getShop_id()!=null){//不为空就是店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    //平台管理员或店铺管理员都可以看：寻主池中的消息shopId is null。只要是state=3，shopId就是null
    @Override
    public PageList<SearchMasterMsg> pool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);

        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        query.setShopId(employee.getShop_id());

        return super.queryPage(query);
    }

    //店铺管理员不能查询以完成的寻主消息：可以通过菜单权限或资源权限来限制
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);

        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        query.setShopId(employee.getShop_id());

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(OrderDto orderDto) {
        //一：判断当前订单是否正在处理
        OrderPetAcquisition dbOrder = orderPetAcquisitionMapper.findByMsgId(orderDto.getMsgId());
        if(dbOrder!=null && dbOrder.getState() == 0){//有订单 = 正在处理
            throw new BusinessException("订单正在处理，请勿重复接单");
        }

        //二：生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.findById(orderDto.getMsgId());
        OrderPetAcquisition order = orderDto2Order(orderDto,msg);
        orderPetAcquisitionMapper.add(order);

        //三：通知接单人 - 发短信
        //Employee employee = employeeMapper.loadById(orderDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");

    }

    private OrderPetAcquisition orderDto2Order(OrderDto orderDto,SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //三天时间没有接单的话就自动取消 -> 定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3*2*60*60*1000));
        order.setPrice(msg.getPrice());
        //支付类型 - 确认订单才设置
        //宠物id - 确认订单，接回宠物再设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(orderDto.getMsgId());
        return order;
    }
}
